package com.example.demo;

import org.apache.logging.log4j.util.PropertiesUtil;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.*;
import java.net.URLDecoder;
import java.util.*;

/**
 * 文件读写
 *
 * @author yanzb
 */
public class ReadFile {
    private List<String> list;
    private Map<String,Object> map;
    private File file;


    public ReadFile(String path, String fileName) {
        list = new ArrayList<String>();
        map = new HashMap<>();
        this.file = this.getFile(path, fileName);
        this.readFile();
    }

    /**
     * 文件搜索
     * 第二个参数如果为空，则默认从项目根目录开始搜索
     *
     * @param fileName //文件名
     * @param path     //路径名
     * @return 搜索结果
     */
    public File findFile(String fileName, String path) {
        if (path == null || path.equals("")) {
            path = new File("").getAbsolutePath();
            path = path.replaceAll("bin", "");
        }
        File file = new File(path);
        if (file.isDirectory()) {
            List<File> fileList = new ArrayList<File>();
            fileList.add(file);
            file = null;
            for (int x = 0; x < fileList.size(); x++) {
                File[] files = fileList.get(x).listFiles();
                for (int i = 0; i < files.length; i++) {
                    if (files[i].getName().equals(fileName)) {
                        file = files[i];
                        files = null;
                        break;
                    } else if (files[i].isDirectory()) {
                        fileList.add(files[i]);
                    }
                }
                if (files == null) {
                    break;
                }
            }
            fileList = null;
            return file;
        } else {
            return null;
        }
    }

    /**
     * 文件获取
     *
     * @param fileName 文件名
     * @return 文件引用
     */
    private File getFile(String path, String fileName) {
        return new File(path + "//" + fileName);
    }

    /**
     * 文件加载
     */
    private void readFile() {
        try {
            FileInputStream fin = new FileInputStream(file);
            InputStreamReader in = new InputStreamReader(fin, "utf-8");
            BufferedReader bin = new BufferedReader(in);
            boolean isEdd = false;
            while (!isEdd) {
                String str = bin.readLine();
                if (str != null) {
                    list.add(str);
                } else {
                    isEdd = true;
                }
            }
            bin.close();
            in.close();
            fin.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 重写缓存
     *
     * @param key 对应键
     * @param val 对应值
     * @return
     */
    public void writeList(String key, String val) {
        for (int i = 0; i < list.size(); i++) {
            String str = list.get(i);
            String[] str_ = str.split("=", 2);
            if (str_[0].equals(key)) {
                str_[1] = val;
                str = str_[0] + "=" + str_[1];
                list.set(i, str);
            }
        }
    }

    /**
     * 读取缓存
     *
     * @param key 对应键
     * @return 缓存值
     */
    public String readList(String key) {
        String val = null;
        for (int i = 0; i < list.size(); i++) {
            String str = list.get(i);
            String[] str_ = str.split("=", 2);
            if (str_[0].equals(key)) {
                val = str_[1];
            }
        }
        return val;
    }

    public int writeFile() {
        try {
            FileOutputStream fout = new FileOutputStream(file, false);
            OutputStreamWriter out = new OutputStreamWriter(fout, "utf-8");
            BufferedWriter bout = new BufferedWriter(out);
            for (int i = 0; i < list.size(); i++) {
                bout.flush();
                bout.write(list.get(i));
                bout.newLine();
            }
            bout.close();
            out.close();
            fout.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 传递键值对的Map，更新properties文件
     *
     * @param fileName
     *            文件名(放在resource源包目录下)，需要后缀
     * @param keyValueMap
     *            键值对Map
     */
    public static void updateProperties(String fileName,Map<String, String> keyValueMap) {
        //getResource方法使用了utf-8对路径信息进行了编码，当路径中存在中文和空格时，他会对这些字符进行转换，这样，
        //得到的往往不是我们想要的真实路径，在此，调用了URLDecoder的decode方法进行解码，以便得到原始的中文及空格路径。
        String filePath = PropertiesUtil.class.getClassLoader().getResource(fileName).getFile();
        Properties props = null;
        BufferedWriter bw = null;

        try {
            filePath = URLDecoder.decode(filePath,"utf-8");
            props = PropertiesLoaderUtils.loadProperties(new ClassPathResource(fileName));

            // 写入属性文件
            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath)));

            props.clear();// 清空旧的文件

            for (String key : keyValueMap.keySet())
                props.setProperty(key, keyValueMap.get(key));

            props.store(bw, "");
        } catch (IOException e) {
        } finally {
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public Map<String, String> getProperties(String fileName){
        Properties props = new Properties();
        Map<String, String> map=new HashMap<String, String>();
        try {
            InputStream in= getClass().getResourceAsStream(fileName);
            props.load(in);
            Enumeration en=props.propertyNames();
            while (en.hasMoreElements()) {
                String key=(String) en.nextElement();
                String property=props.getProperty(key);
                map.put(key, property);
                System.out.println(key + "."+property);
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return map;
    }

    public static void main(String[] args) {

    }

}
